/**
 * 用流去读写文件
 * 
 */
// let startAt = Date.now();
let fs = require("fs");
// for(let i=0;i<20000;i++){
//  //writeFileSync 内部封装了 fopen fwrite fend
//  fs.writeFileSync('./big1.txt','今天学习流文件的读写,还不知道难不难\n',{flag:'a'});
// }
// let endAt=Date.now();//34秒

// console.log(endAt-startAt);
// let fd=fs.openSync('./big2.txt','w');
// for(let j=0;j<500000;j++){
//     let str='今天学习流文件的读写,还不知道难不难\n';
//     fs.writeSync(fd,Buffer.from(str));
// }
// fs.closeSync(fd);
// let endAt2=Date.now();
// console.log(endAt2-endAt);//403毫秒

//怎么证明.readfile 耗费的内存
//如果说我运行前的内存 ------运行后的内存

let os = require("os");
let startMem=os.freemem();//运行前空闲的内存
// console.log(startMem);
// let fd=fs.openSync('./big2.txt','r');
// let bf2= Buffer.alloc(25.2*1024*1024)
// fs.readSync(fd,bf2,0,25.2*1024*1024);//30m
fs.readFileSync('./big2.txt');//fopen fread fclose
let endMem=os.freemem();//打开后空闲的内存
console.log((startMem-endMem)/1024/1024);
//fs.closeSync(fd);

/**
 * stream的读取
 * createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions)
 * path 文件路径
 * option 
 *      flags?: 标识
        encoding?: 编码
    应用场景：读取大文件    
 */

let readStram=fs.createReadStream('./stream.txt',{encoding:'utf-8'});

// stram on 绑定 data 
readStram.on('data',function(chunk){
    console.log(chunk+'==================');
});

setTimeout(() => {
    readStram.close();//把流关闭
}, 5);

/**
 * stram open 打开文件时触发事件
 */
readStram.on('open',function(fd){
    console.log('文件描述符号'+fd);
});
/**
 * stram end 表示数据流完了
 */
readStram.on('end',function(){
    console.log('i am end 数据流完了');
})
/**
 * stram close 关闭流
 */
readStram.on('close',function(){
    console.log('i am close ');
});

/**
 * 文件流的写入
 * createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions)
 * path 文件路劲
 * BufferEncoding 编码
 * 文件不存在自动创建
 * 
 */
let writeStream=fs.createWriteStream('./stream/write2.txt','utf-8');
//write 流入数据 参数 chunk string 或者是 buffer 可循环写入
let bf2='失恋一次不可怕，可以再来一次\n';
writeStream.write(Buffer.from(bf2));
writeStream.write(Buffer.from(bf2));
writeStream.write(Buffer.from(bf2));
writeStream.write(Buffer.from(bf2));
writeStream.write(Buffer.from(bf2));
writeStream.write(Buffer.from(bf2));
writeStream.close();

/**
 * pipe 中文管道 
 *      
*/

let readStram2 = fs.createReadStream('./stream/write2.txt',{encoding:'utf-8'});
let writeStream2= fs.createWriteStream('./stream/write3.txt');
/**
 * pipe 接入水管后,绑定数据流
 */
readStram2.pipe(writeStream2);

/**
 * 作业
 * 创建一个大文件，然后去计算一下流方式读取的内存消耗
 * 
 */














